package com.bsoft.ecommerce.service.async;

import com.bsoft.ecommerce.constant.AsyncTaskStatusEnum;
import com.bsoft.ecommerce.vo.AsyncTaskInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

//异步任务执行监控切面
@Slf4j
@Aspect
@Component

public class AsynTaskMonitor {
     //注入异步任务管理器
    private final AsynTaskManager asynTaskManager;

    public AsynTaskMonitor(AsynTaskManager asynTaskManager) {
        this.asynTaskManager = asynTaskManager;
    }

    //环绕通知
    //环绕切面让我们可以在方法执行之前和执行之后做一些 操作
    @Around("execution(* com.bsoft.ecommerce.service.async.AsynServiceImpl.*(..))")
    public Object taskHandle(ProceedingJoinPoint proceedingJoinPoint){

        //获取 taskid
        String taskId = proceedingJoinPoint.getArgs()[1].toString();
        //获取任务信息 在提交任务的时候就已经放入到容器中
        AsyncTaskInfo taskInfo= asynTaskManager.getTaskInfo(taskId);
        log.info("Asyntask");
        taskInfo.setStatus(AsyncTaskStatusEnum.RUNNING);
        asynTaskManager.setTaskInfo(taskInfo);

        AsyncTaskStatusEnum  statusEnum = null;
        Object result = null;
        try {
             result=   proceedingJoinPoint.proceed();
             statusEnum = AsyncTaskStatusEnum.SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            result = null;
            statusEnum = AsyncTaskStatusEnum.FAILED;
        }
        //设置异步任务的其他信息
        taskInfo.setEndTime(new Date());
        taskInfo.setStatus(statusEnum);
        taskInfo.setTotalTime(String.valueOf(taskInfo.getEndTime().getTime()-taskInfo.getStartTime().getTime()));
        asynTaskManager.setTaskInfo(taskInfo);
        return result;
    }

}
